use rama::extensions::{Extensions, ExtensionsMut, ExtensionsRef};
use rama::http::Request;
use rama::http::client::HttpConnector;
use rama::http::proto::h1::Http1HeaderMap;
use rama::http::server::HttpServer;
use rama::http::{Body, Response};
use rama::http::{HeaderName, HeaderValue};
use rama::net::client::EstablishedClientConnection;
use rama::net::fingerprint::{Ja3, Ja4, Ja4H};
use rama::net::tls::ApplicationProtocol;
use rama::net::tls::client::ServerVerifyMode;
use rama::net::tls::client::parse_client_hello;
use rama::net::tls::server::ServerAuth;
use rama::net::tls::server::ServerConfig;
use rama::rt::Executor;
use rama::service::service_fn;
use rama::tls::boring::client::TlsConnector;
use rama::tls::boring::client::{EmulateTlsProfileLayer, TlsConnectorDataBuilder};
use rama::tls::boring::server::TlsAcceptorLayer;
use rama::ua::layer::emulate::{
    SelectedUserAgentProfile, UserAgentEmulateHttpConnectModifier,
    UserAgentEmulateHttpRequestModifier, UserAgentEmulateLayer,
};
use rama::ua::profile::HttpProfile;
use rama::ua::profile::UserAgentDatabase;
use rama::ua::profile::{
    Http1Profile, Http1Settings, Http2Profile, Http2Settings, HttpHeadersProfile,
};
use rama::ua::profile::{TlsProfile, UserAgentProfile};
use rama::ua::{PlatformKind, UserAgentKind};
use rama::{Layer, Service};
use rama_http::layer::version_adapter::RequestVersionAdapter;
use std::convert::Infallible;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use tokio::io::duplex;
use tokio::task::JoinSet;

#[derive(Debug)]
struct TestCase {
    description: &'static str,
    uri: &'static str,
    ua_kind: UserAgentKind,
    ua_platform: Option<PlatformKind>,
    ua_version: Option<usize>,
    tls_client_hello_data: &'static [u8],
    http_profile: HttpProfile,
    expected: TestCaseExpected,
}

#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
struct TestCaseExpected {
    ja4: &'static str,
    ja4h: &'static str,
    ja3: &'static str,
}

#[tokio::test]
async fn test_ua_emulation() {
    let test_cases = [
        TestCase {
            description: "MacOS Firefox 135 at 2025-03-09 @ https://echo.ramaproxy.org",
            uri: "https://echo.ramaproxy.org",
            ua_kind: UserAgentKind::Firefox,
            ua_platform: Some(PlatformKind::MacOS),
            ua_version: Some(135),
            tls_client_hello_data: &[
                0x03, 0x03, 0x6e, 0x28, 0x6d, 0x09, 0x00, 0xef, 0xbc, 0xf9, 0x0b, 0xbd, 0x5a, 0x4b,
                0xbf, 0xe7, 0xfb, 0x3c, 0x1a, 0x17, 0xc0, 0xfe, 0x9e, 0x6a, 0x44, 0xea, 0x84, 0x1c,
                0x87, 0xbb, 0x19, 0xc7, 0xc2, 0x63, 0x20, 0xc8, 0xf0, 0x5d, 0x66, 0x66, 0x55, 0x11,
                0x0a, 0x15, 0xd2, 0x2c, 0x77, 0x36, 0x1d, 0x18, 0x54, 0x6e, 0x85, 0x45, 0x43, 0xe1,
                0x4b, 0x8f, 0x79, 0xfd, 0x19, 0xa0, 0x5b, 0x74, 0x3b, 0xfd, 0x60, 0x00, 0x22, 0x13,
                0x01, 0x13, 0x03, 0x13, 0x02, 0xc0, 0x2b, 0xc0, 0x2f, 0xcc, 0xa9, 0xcc, 0xa8, 0xc0,
                0x2c, 0xc0, 0x30, 0xc0, 0x0a, 0xc0, 0x09, 0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00,
                0x9d, 0x00, 0x2f, 0x00, 0x35, 0x01, 0x00, 0x06, 0xfb, 0x00, 0x00, 0x00, 0x17, 0x00,
                0x15, 0x00, 0x00, 0x12, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x72, 0x61, 0x6d, 0x61, 0x70,
                0x72, 0x6f, 0x78, 0x79, 0x2e, 0x6f, 0x72, 0x67, 0x00, 0x17, 0x00, 0x00, 0xff, 0x01,
                0x00, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x0e, 0x11, 0xec, 0x00, 0x1d, 0x00,
                0x17, 0x00, 0x18, 0x00, 0x19, 0x01, 0x00, 0x01, 0x01, 0x00, 0x0b, 0x00, 0x02, 0x01,
                0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x0c, 0x02, 0x68, 0x32,
                0x08, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x05, 0x00, 0x05, 0x01,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x0a, 0x00, 0x08, 0x04, 0x03, 0x05, 0x03,
                0x06, 0x03, 0x02, 0x03, 0x00, 0x12, 0x00, 0x00, 0x00, 0x33, 0x05, 0x2f, 0x05, 0x2d,
                0x11, 0xec, 0x04, 0xc0, 0x08, 0x87, 0x91, 0xd4, 0xcc, 0x79, 0xc2, 0x4c, 0x1d, 0xc1,
                0xd5, 0xa1, 0xfb, 0x64, 0x6b, 0x79, 0x1b, 0x8d, 0xb5, 0xcc, 0x7a, 0xd9, 0x5b, 0x90,
                0xa4, 0x63, 0x1f, 0xd7, 0x16, 0x65, 0x11, 0x50, 0x44, 0xe6, 0x0a, 0x32, 0xef, 0x01,
                0x4d, 0xaf, 0xb7, 0xc0, 0xdd, 0x11, 0xaf, 0xf3, 0x77, 0x69, 0x2b, 0xa2, 0x41, 0xf6,
                0x23, 0x83, 0xd1, 0xaa, 0x81, 0xe5, 0xc6, 0x4a, 0xe6, 0x81, 0x65, 0x21, 0x19, 0x25,
                0xf0, 0x91, 0x29, 0xfc, 0xda, 0x07, 0x57, 0x21, 0x25, 0x7b, 0x34, 0x29, 0xd5, 0xf9,
                0xc1, 0xd7, 0x32, 0x03, 0x26, 0xb4, 0x0d, 0x98, 0x47, 0x42, 0xef, 0x0c, 0x2d, 0x59,
                0x35, 0xa6, 0xa5, 0xb9, 0x3e, 0x64, 0x57, 0xb1, 0x8a, 0x4b, 0xbb, 0x71, 0x18, 0xb4,
                0xec, 0x69, 0xa2, 0x90, 0xd0, 0xb9, 0x2a, 0xf0, 0x41, 0x49, 0x2c, 0x1f, 0x3f, 0x91,
                0x6a, 0x8e, 0x70, 0x53, 0xa8, 0xf9, 0x7e, 0x02, 0x06, 0x67, 0x97, 0x91, 0x4d, 0xd9,
                0x92, 0x46, 0x92, 0xbb, 0x00, 0xd4, 0xf6, 0x95, 0xe7, 0x80, 0x60, 0x50, 0x01, 0xbf,
                0x5d, 0xf2, 0xb3, 0x09, 0x5c, 0x79, 0x8b, 0x23, 0x22, 0x2f, 0x29, 0xc6, 0x77, 0xe8,
                0x64, 0xa1, 0xec, 0x61, 0xe9, 0x59, 0x1b, 0xb2, 0x50, 0x2d, 0x1b, 0x00, 0x79, 0x90,
                0x3b, 0x8e, 0xa5, 0xa8, 0xb9, 0x63, 0x55, 0x8f, 0x96, 0x72, 0x3b, 0x5e, 0xb9, 0xc2,
                0xe9, 0x4a, 0x30, 0x35, 0x1b, 0xcf, 0x3a, 0x1c, 0x1a, 0x69, 0x72, 0x48, 0x3b, 0x0c,
                0x9c, 0x60, 0x5b, 0x45, 0xf9, 0x57, 0x9e, 0x08, 0x60, 0x75, 0xb8, 0x55, 0xcc, 0xe8,
                0x85, 0xa5, 0xdb, 0x7c, 0x47, 0x25, 0x54, 0x0a, 0x91, 0x58, 0x7e, 0xb0, 0x05, 0xa7,
                0x69, 0x71, 0x82, 0x7c, 0x54, 0x57, 0xa7, 0x46, 0xad, 0xdd, 0x0a, 0x53, 0xa4, 0xe6,
                0x47, 0x9d, 0xe5, 0x8d, 0x37, 0xe9, 0x9b, 0x6c, 0x01, 0x8e, 0x49, 0x77, 0xcb, 0x67,
                0xc9, 0x0f, 0xcd, 0xb7, 0x9c, 0xc2, 0x3c, 0xab, 0x5e, 0x10, 0xcf, 0x1a, 0x00, 0x77,
                0x93, 0xda, 0x0d, 0xa1, 0xa5, 0xb7, 0x56, 0xa0, 0x3e, 0xcf, 0xcc, 0x6c, 0x2d, 0x40,
                0x26, 0x1e, 0x8c, 0x29, 0x62, 0x5b, 0x54, 0x9e, 0x15, 0x05, 0xeb, 0xfb, 0x53, 0xb2,
                0x00, 0x1f, 0xa9, 0x92, 0xbf, 0xf2, 0xe8, 0x8f, 0x41, 0xe7, 0xc5, 0x7b, 0x3c, 0x1f,
                0xcb, 0xd4, 0x44, 0x7c, 0x25, 0x5e, 0x04, 0xb5, 0x99, 0x65, 0x7c, 0x01, 0x94, 0x85,
                0x52, 0xd3, 0xc8, 0x8d, 0xfb, 0xc3, 0xc3, 0xeb, 0x92, 0x51, 0xdc, 0xab, 0x61, 0x24,
                0x88, 0x64, 0xb9, 0x1a, 0x15, 0xde, 0xd3, 0x8b, 0xff, 0xa6, 0xa6, 0x9f, 0x53, 0x75,
                0x0d, 0x81, 0x7f, 0x1e, 0x9a, 0x8a, 0x7a, 0x06, 0x95, 0xdf, 0x05, 0x16, 0xa7, 0x9b,
                0x12, 0xd3, 0x97, 0x69, 0xe2, 0xc3, 0xa1, 0x50, 0x31, 0x0b, 0x9d, 0x66, 0xcb, 0x06,
                0x93, 0x39, 0x83, 0x48, 0xac, 0xf9, 0x80, 0x15, 0x0e, 0xb6, 0x9a, 0xec, 0xdc, 0x18,
                0x89, 0xb9, 0x62, 0x6e, 0x32, 0x67, 0xde, 0xa3, 0x53, 0x0d, 0x22, 0x6f, 0xc4, 0x66,
                0xb0, 0x22, 0xc4, 0xbb, 0x72, 0x76, 0x1f, 0xcc, 0xdb, 0x33, 0x24, 0xe9, 0x45, 0x55,
                0x18, 0x31, 0x16, 0x94, 0x28, 0x22, 0x5c, 0x2f, 0xd5, 0x01, 0x13, 0x0d, 0xc4, 0x1d,
                0x4d, 0x30, 0x6a, 0x3e, 0xd8, 0x2b, 0x58, 0xd9, 0x34, 0xc2, 0x04, 0x66, 0x68, 0x1c,
                0x47, 0x3b, 0x23, 0xa1, 0x39, 0x16, 0x34, 0xce, 0x24, 0x09, 0x62, 0x11, 0xa3, 0xda,
                0xd0, 0x23, 0x90, 0x24, 0x10, 0xa9, 0x42, 0x3b, 0xa2, 0x72, 0x12, 0x22, 0xc4, 0x67,
                0x3f, 0x56, 0x81, 0x9f, 0x65, 0x8b, 0x50, 0x54, 0x62, 0x15, 0xa5, 0xc3, 0x69, 0x51,
                0xc3, 0x8a, 0x31, 0xb9, 0xd6, 0xd5, 0xb1, 0x02, 0xa1, 0x93, 0x70, 0x3c, 0x89, 0xb3,
                0x69, 0x73, 0x23, 0x31, 0x34, 0xfc, 0xd7, 0xc1, 0x34, 0x5b, 0x05, 0x8f, 0x56, 0x03,
                0xc4, 0xa2, 0x32, 0xf2, 0xfc, 0x19, 0x84, 0x85, 0xc6, 0xd4, 0xb3, 0x1d, 0x8d, 0x06,
                0x83, 0x36, 0x44, 0x37, 0x81, 0x72, 0x7b, 0xe6, 0x20, 0x85, 0x38, 0x82, 0x66, 0x6c,
                0x56, 0x39, 0xc8, 0x3b, 0x92, 0x08, 0x68, 0x8e, 0xf2, 0x2a, 0xc9, 0x5b, 0xa9, 0x4e,
                0xc2, 0x45, 0x27, 0x14, 0x47, 0x87, 0xac, 0xb0, 0xa0, 0x40, 0x59, 0xc6, 0x65, 0x41,
                0x46, 0xcb, 0xa2, 0x59, 0x38, 0x57, 0x88, 0xa9, 0x01, 0x25, 0x49, 0xb1, 0x8a, 0x87,
                0x67, 0x07, 0x8e, 0x1a, 0xc7, 0x89, 0xf7, 0x82, 0x02, 0x16, 0xac, 0x93, 0xfc, 0xa3,
                0x75, 0xcb, 0x0a, 0x1d, 0x84, 0x94, 0xc5, 0x8a, 0xce, 0xc3, 0x17, 0x81, 0x02, 0x9c,
                0xa5, 0xb7, 0xf8, 0x02, 0x17, 0x75, 0x0b, 0x1b, 0xb9, 0x9d, 0x6b, 0x8c, 0x7f, 0x46,
                0x90, 0x67, 0xef, 0x0c, 0xa4, 0xa5, 0xf7, 0x3d, 0x14, 0x9c, 0x1e, 0x7f, 0x6a, 0x3d,
                0x66, 0x73, 0x91, 0xae, 0x68, 0x75, 0x1e, 0xd5, 0xc0, 0x99, 0xac, 0x5f, 0x35, 0xd7,
                0xbd, 0xe3, 0x9c, 0x1c, 0x45, 0x36, 0x18, 0x2a, 0x0a, 0xd0, 0x2b, 0xb6, 0xab, 0x92,
                0x27, 0x0c, 0x71, 0x64, 0x19, 0x8c, 0x53, 0xb7, 0x5c, 0x43, 0x12, 0x25, 0xc8, 0xc6,
                0xeb, 0xa7, 0x43, 0xe1, 0x15, 0x27, 0xfa, 0x66, 0x96, 0x25, 0xa0, 0x47, 0x36, 0x50,
                0x34, 0xd4, 0x48, 0x1c, 0x36, 0x95, 0x04, 0x36, 0x4c, 0xa6, 0x3c, 0x62, 0x1d, 0x66,
                0xc4, 0x10, 0x3c, 0xd4, 0x54, 0x69, 0x9c, 0x49, 0x96, 0x35, 0x50, 0x29, 0xa9, 0x4c,
                0x14, 0xf2, 0x4c, 0x13, 0xb8, 0x51, 0x35, 0x66, 0x3d, 0x69, 0x6b, 0x4f, 0x2b, 0x32,
                0x23, 0xdd, 0x64, 0x7f, 0x79, 0xb8, 0xa8, 0xff, 0xdb, 0xbd, 0x5e, 0x87, 0x19, 0x35,
                0xb7, 0x6e, 0xaf, 0x5b, 0x89, 0xe6, 0x1b, 0x55, 0x6e, 0xb5, 0x20, 0x24, 0x94, 0xcb,
                0xfc, 0x59, 0x8f, 0xea, 0x54, 0xab, 0xbf, 0x30, 0xcf, 0xb3, 0x7c, 0xb3, 0xde, 0x82,
                0x20, 0xfb, 0xa2, 0xba, 0xda, 0x4b, 0x1e, 0xa7, 0xa7, 0x52, 0x31, 0xc5, 0x88, 0x1d,
                0x3a, 0x22, 0xc6, 0x10, 0x6f, 0x31, 0xc6, 0x32, 0x97, 0x39, 0x05, 0xa5, 0xa8, 0x26,
                0xc9, 0x7b, 0xb1, 0x01, 0xf1, 0xa4, 0x9a, 0x16, 0x1e, 0x88, 0xf4, 0x7e, 0xd4, 0xaa,
                0x7c, 0x3e, 0xe2, 0x47, 0x9e, 0x8a, 0x82, 0x84, 0xc6, 0x1b, 0xf5, 0x82, 0xc7, 0x05,
                0xb4, 0x98, 0xb1, 0xfc, 0x78, 0x6e, 0x4b, 0xb5, 0x8e, 0xeb, 0x2d, 0xfb, 0x12, 0x8a,
                0x2c, 0xf7, 0x75, 0x5d, 0x22, 0xbb, 0x34, 0x1a, 0xce, 0x46, 0x55, 0x4e, 0xec, 0x6a,
                0x35, 0x64, 0x13, 0x21, 0x21, 0x61, 0x8e, 0xf6, 0x46, 0xc4, 0x94, 0xe8, 0xbc, 0x64,
                0x3c, 0x06, 0x28, 0xf1, 0x33, 0x0c, 0xc7, 0x12, 0x40, 0xab, 0xa4, 0xab, 0x67, 0x2d,
                0x1a, 0x30, 0x03, 0xff, 0x18, 0xa0, 0x9a, 0x47, 0x7a, 0x38, 0x34, 0x85, 0xae, 0xd7,
                0xc7, 0x7b, 0x68, 0x34, 0x44, 0xa7, 0xa7, 0x59, 0xc4, 0x42, 0xae, 0x63, 0x4a, 0x4b,
                0x79, 0x07, 0x92, 0x4a, 0x29, 0x5d, 0x7c, 0x4e, 0x21, 0x44, 0xc8, 0x68, 0xa5, 0x35,
                0x15, 0xe9, 0x02, 0xb8, 0xc0, 0x7b, 0xe0, 0x04, 0x7b, 0x96, 0xb5, 0xa7, 0xd3, 0x05,
                0x6c, 0x14, 0xa7, 0xbc, 0x54, 0x75, 0x13, 0x8e, 0x45, 0x03, 0x49, 0x44, 0x60, 0x78,
                0x77, 0x8f, 0x9f, 0x56, 0x1c, 0x02, 0x62, 0xcf, 0x8e, 0x86, 0xbe, 0xe7, 0x40, 0x8e,
                0xdc, 0x96, 0xc1, 0xbd, 0x65, 0x5b, 0x45, 0x0c, 0xc5, 0xd1, 0xd3, 0xbc, 0xed, 0x94,
                0x80, 0x14, 0xeb, 0x7c, 0xf1, 0xca, 0x1f, 0x25, 0xbc, 0x00, 0xeb, 0x03, 0x94, 0xd7,
                0x51, 0x33, 0x75, 0x41, 0x4b, 0x58, 0x02, 0x35, 0x78, 0xf3, 0x9a, 0xc7, 0x30, 0x92,
                0xfc, 0xa5, 0x24, 0x9a, 0x71, 0x5a, 0x92, 0x27, 0xce, 0xd7, 0xfc, 0x4e, 0xfd, 0xe7,
                0xa1, 0x35, 0xd3, 0x5b, 0x78, 0xa3, 0x2e, 0xd3, 0x74, 0x7e, 0xa3, 0xf3, 0x0b, 0xb1,
                0x47, 0x0d, 0x1f, 0xcc, 0x36, 0xb8, 0xf7, 0xc3, 0x5c, 0x67, 0x43, 0x24, 0x45, 0x1d,
                0x1e, 0xf8, 0x50, 0xd0, 0x93, 0x25, 0x98, 0x59, 0x4d, 0xb2, 0x57, 0x60, 0x7d, 0xe5,
                0xba, 0xe9, 0x72, 0x3d, 0xe2, 0xe1, 0x73, 0xb7, 0x4c, 0x78, 0x90, 0x55, 0x17, 0xc4,
                0xf0, 0x71, 0xdd, 0x4c, 0x33, 0x3b, 0xa7, 0x49, 0x70, 0x15, 0x52, 0xe7, 0xe1, 0x39,
                0x9b, 0x29, 0x52, 0x16, 0x8a, 0x69, 0x49, 0xa9, 0x6d, 0xde, 0xf1, 0x24, 0x87, 0xf3,
                0xbe, 0xa9, 0x93, 0x0b, 0x8a, 0x8b, 0x76, 0x48, 0x84, 0x86, 0x6c, 0xd4, 0x73, 0xe3,
                0x5a, 0x41, 0xde, 0x4c, 0xcd, 0x2d, 0x35, 0xa0, 0x88, 0x3e, 0x77, 0xce, 0x0f, 0xe1,
                0xc3, 0x95, 0x10, 0x82, 0x3a, 0xa7, 0x4c, 0x0e, 0xef, 0xf7, 0xc0, 0xb9, 0x43, 0xe8,
                0xf7, 0xe4, 0x03, 0x8b, 0xcf, 0x72, 0xbd, 0x14, 0xab, 0xbb, 0x3c, 0xd2, 0xc9, 0x28,
                0x1c, 0x1a, 0x87, 0xab, 0x65, 0x82, 0x14, 0xda, 0xba, 0x04, 0xf4, 0xb4, 0x37, 0xbc,
                0x91, 0x81, 0xcb, 0x48, 0x99, 0x7a, 0xbc, 0xda, 0x9c, 0x81, 0x00, 0x10, 0x4c, 0x48,
                0x06, 0x2e, 0x00, 0x1d, 0x00, 0x20, 0xc9, 0x28, 0x1c, 0x1a, 0x87, 0xab, 0x65, 0x82,
                0x14, 0xda, 0xba, 0x04, 0xf4, 0xb4, 0x37, 0xbc, 0x91, 0x81, 0xcb, 0x48, 0x99, 0x7a,
                0xbc, 0xda, 0x9c, 0x81, 0x00, 0x10, 0x4c, 0x48, 0x06, 0x2e, 0x00, 0x17, 0x00, 0x41,
                0x04, 0x49, 0xbd, 0xf3, 0x99, 0xf4, 0x5d, 0x8a, 0x73, 0x94, 0xcb, 0x53, 0x20, 0x86,
                0x93, 0x02, 0x5d, 0x91, 0x08, 0x17, 0xaa, 0xce, 0x10, 0xa9, 0xbb, 0xde, 0x85, 0xd1,
                0xe2, 0x5c, 0x59, 0x0a, 0xca, 0x2e, 0xec, 0x7b, 0xd9, 0xf2, 0x67, 0x85, 0xe5, 0xb2,
                0x3d, 0x3f, 0x98, 0x86, 0x42, 0x90, 0x73, 0xcf, 0xe3, 0x6f, 0xa2, 0x53, 0xc3, 0x7d,
                0x3c, 0xae, 0xd3, 0x16, 0x8c, 0xde, 0xa8, 0x22, 0x95, 0x00, 0x2b, 0x00, 0x05, 0x04,
                0x03, 0x04, 0x03, 0x03, 0x00, 0x0d, 0x00, 0x18, 0x00, 0x16, 0x04, 0x03, 0x05, 0x03,
                0x06, 0x03, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01,
                0x02, 0x03, 0x02, 0x01, 0x00, 0x2d, 0x00, 0x02, 0x01, 0x01, 0x00, 0x1c, 0x00, 0x02,
                0x40, 0x01, 0x00, 0x1b, 0x00, 0x07, 0x06, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0xfe,
                0x0d, 0x01, 0x19, 0x00, 0x00, 0x01, 0x00, 0x03, 0xb6, 0x00, 0x20, 0xd9, 0x62, 0x90,
                0x3a, 0xfe, 0xd8, 0x30, 0x61, 0xe5, 0x78, 0x34, 0xe2, 0x7e, 0x81, 0xd5, 0x11, 0x1c,
                0xa8, 0x13, 0x4b, 0xfd, 0xbc, 0x0d, 0x56, 0x74, 0x31, 0xd3, 0xd0, 0x7a, 0xb1, 0x71,
                0x08, 0x00, 0xef, 0xba, 0x01, 0x6c, 0x16, 0x4b, 0xf6, 0xaa, 0x2e, 0xd9, 0x4e, 0x1f,
                0x2f, 0x23, 0x42, 0x47, 0x54, 0x50, 0x55, 0xfa, 0x82, 0xcf, 0xb6, 0xed, 0x58, 0x7c,
                0x94, 0x14, 0xc1, 0x6e, 0x15, 0x2e, 0xe1, 0x0a, 0x1f, 0xec, 0x92, 0x80, 0xc1, 0x85,
                0xad, 0xa0, 0x25, 0x67, 0xee, 0x6b, 0x30, 0xee, 0x0e, 0xd6, 0x81, 0x62, 0x24, 0x12,
                0xc8, 0x4a, 0x75, 0x1b, 0x04, 0x83, 0x04, 0x75, 0xfd, 0x3b, 0xd3, 0x0b, 0xa3, 0x03,
                0x6c, 0x0c, 0xa1, 0x40, 0x12, 0xfa, 0x82, 0x7d, 0xfa, 0x4b, 0x33, 0x0a, 0x68, 0x79,
                0x5b, 0xa2, 0x59, 0xf1, 0x3b, 0xbc, 0xf8, 0xf8, 0x33, 0x5d, 0x9a, 0x7e, 0xd2, 0x01,
                0x0b, 0x4e, 0x5c, 0x6e, 0xd6, 0xd5, 0x7e, 0x9a, 0x4c, 0x99, 0xaa, 0x47, 0xd0, 0xf7,
                0x75, 0xd7, 0x3b, 0x14, 0x55, 0x21, 0x9f, 0xcf, 0x59, 0x22, 0xf3, 0x07, 0x11, 0x9e,
                0x51, 0xa9, 0xba, 0x73, 0x9c, 0xea, 0x11, 0xc8, 0x03, 0xf6, 0x8e, 0x31, 0x65, 0x6c,
                0xc2, 0x26, 0x00, 0xa5, 0xb5, 0xfb, 0xa0, 0x2f, 0x6b, 0xac, 0x04, 0x51, 0x53, 0x41,
                0xa0, 0xee, 0xad, 0xc6, 0x93, 0xc6, 0x78, 0xc9, 0xd0, 0x6a, 0xf0, 0xcc, 0x97, 0x14,
                0x20, 0x4d, 0x94, 0x1d, 0xf5, 0xa6, 0x82, 0x37, 0xfa, 0xbd, 0xe9, 0x02, 0x37, 0x69,
                0x28, 0x86, 0x77, 0x08, 0x3c, 0xd1, 0xd0, 0xed, 0xad, 0x7c, 0x78, 0xa3, 0xdb, 0xe9,
                0x29, 0x29, 0x74, 0xe3, 0x0a, 0x79, 0x70, 0x30, 0xd4, 0xfd, 0x34, 0x63, 0xa9, 0xd6,
                0x71, 0xe0, 0x8e, 0x6a, 0x59, 0x69, 0x63, 0xcc, 0x43, 0x81, 0x25, 0xe1, 0x0e, 0xf2,
                0x0d, 0xe1, 0xb5, 0x92, 0xab, 0xe0, 0xc1, 0x87, 0x41, 0xf9, 0x55, 0xba, 0x68, 0x4d,
                0x70, 0x73, 0x79, 0x80,
            ],
            http_profile: HttpProfile {
                h1: Arc::new(Http1Profile {
                    headers: HttpHeadersProfile {
                        navigate: Http1HeaderMap::default(),
                        fetch: None,
                        xhr: None,
                        form: None,
                        ws : None,
                    },
                    settings: Http1Settings::default(),
                }),
                h2: Arc::new(Http2Profile {
                    headers: HttpHeadersProfile {
                        navigate: [
                            (HeaderName::from_static("user-agent"), HeaderValue::from_static("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:135.0) Gecko/20100101 Firefox/135.0")),
                            (HeaderName::from_static("accept"), HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")),
                            (HeaderName::from_static("accept-language"), HeaderValue::from_static("en-US,en;q=0.5")),
                            (HeaderName::from_static("accept-encoding"), HeaderValue::from_static("gzip, deflate, br, zstd")),
                            (HeaderName::from_static("upgrade-insecure-requests"), HeaderValue::from_static("1")),
                            (HeaderName::from_static("sec-fetch-dest"), HeaderValue::from_static("document")),
                            (HeaderName::from_static("sec-fetch-mode"), HeaderValue::from_static("navigate")),
                            (HeaderName::from_static("sec-fetch-site"), HeaderValue::from_static("none")),
                            (HeaderName::from_static("sec-fetch-user"), HeaderValue::from_static("?1")),
                            (HeaderName::from_static("dnt"), HeaderValue::from_static("1")),
                            (HeaderName::from_static("sec-gpc"), HeaderValue::from_static("1")),
                            (HeaderName::from_static("priority"), HeaderValue::from_static("u=0, i")),
                            (HeaderName::from_static("te"), HeaderValue::from_static("trailers")),
                        ].into_iter().collect(),
                        fetch: None,
                        xhr: None,
                        form: None,
                        ws : None,
                    },
                    settings: Http2Settings::default(),
                }),
            },
            expected: TestCaseExpected {
                ja4: "t13d1717h2_5b57614c22b0_3cbfd9057e0d",
                ja4h: "ge20nn13enus_dee81a311bfc_000000000000_000000000000",
                ja3: "6f7889b9fb1a62a9577e685c1fcfa919",
            },
        },
    ];

    for test_case in test_cases {
        let expected = test_case.expected;
        let description = test_case.description;

        #[derive(Debug, Clone)]
        struct State {
            expected: TestCaseExpected,
            description: &'static str,
        }

        async fn server_svc_fn(req: Request) -> Result<Response, Infallible> {
            let state = req.extensions().get::<State>().unwrap();
            let expected = state.expected;
            let description = state.description;

            println!("server receives {description}: {expected:?}");

            let ja4h = Ja4H::compute(&req).expect(description);
            println!("server receives {description}: ja4h: {ja4h:?}");
            assert_eq!(ja4h.to_string(), expected.ja4h, "{description}");

            // TODO: enable ja3 + ja4 tests
            // once we support more tls extensions

            let ja4 = Ja4::compute(req.extensions()).expect(description);
            println!("server receives {description}: ja4: {ja4:?}");
            // assert_eq!(ja4.to_string(), expected.ja4, "{}", description);

            let ja3 = format!("{:x}", Ja3::compute(req.extensions()).expect(description));
            println!("server receives {description}: ja3: {ja3:?}");
            // assert_eq!(ja3, expected.ja3, "{}", description);

            Ok(Response::new(Body::empty()))
        }

        let client_hello = parse_client_hello(test_case.tls_client_hello_data).expect(description);

        let profile = UserAgentProfile {
            ua_kind: test_case.ua_kind,
            ua_version: test_case.ua_version,
            platform: test_case.ua_platform,
            http: test_case.http_profile,
            tls: TlsProfile {
                client_config: Arc::new(client_hello.into()),
                ws_client_config_overwrites: None,
            },
            runtime: None,
        };

        let client = (
            UserAgentEmulateLayer::new(Arc::new(profile)),
            EmulateTlsProfileLayer::new(),
        )
            .into_layer(service_fn(async |mut req: Request| {
                // We can edit our current builder directly or create a new one if needed
                let mut builder = req
                    .extensions_mut()
                    .get::<TlsConnectorDataBuilder>()
                    .cloned()
                    .unwrap_or_default();
                builder.set_server_verify_mode(ServerVerifyMode::Disable);
                req.extensions_mut().insert(builder);

                // We dont need to set connector data on TlsConnector as it will get it from extensions
                let connector = HttpConnector::new(UserAgentEmulateHttpConnectModifier::new(
                    RequestVersionAdapter::new(TlsConnector::secure(MockConnectorService::new(
                        service_fn(server_svc_fn),
                    ))),
                ))
                .with_svc_req_inspector(UserAgentEmulateHttpRequestModifier::default());

                let EstablishedClientConnection { req, conn } =
                    connector.serve(req).await.expect(description);

                Ok::<_, Infallible>(conn.serve(req).await.expect(description))
            }));

        let mut server_extensions = Extensions::new();
        server_extensions.insert(State {
            expected,
            description,
        });

        let req = Request::builder()
            .uri(test_case.uri)
            .extension(ServerExtensions(server_extensions))
            .body(Body::empty())
            .unwrap();

        client.serve(req).await.expect(description);
    }
}

#[tokio::test]
async fn test_ua_embedded_profiles_are_all_resulting_in_correct_traffic_flow() {
    let ua_db = UserAgentDatabase::embedded();
    assert!(!ua_db.is_empty(), "no profiles found");

    let counter = Arc::new(AtomicUsize::new(0));

    let mut handles = JoinSet::new();
    for profile in ua_db.iter() {
        let profile = Arc::new(profile.clone());
        let counter = counter.clone();

        handles.spawn(async move {
            #[derive(Debug, Clone)]
            struct State {
                counter: Arc<AtomicUsize>,
            }

            async fn server_svc_fn(req: Request) -> Result<Response, Infallible> {
                req.extensions()
                    .get::<State>()
                    .unwrap()
                    .counter
                    .fetch_add(1, std::sync::atomic::Ordering::Release);
                Ok(Response::new(Body::empty()))
            }

            // We create a base config that will overwrite TlsProfile setting so we don't
            // need to apply it to each Context. See `test_ua_emulation`` for how to set it on
            // the Context instead
            let tls_config = TlsConnectorDataBuilder::new()
                .with_server_verify_mode(ServerVerifyMode::Disable)
                .into_shared_builder();

            let client = (
                UserAgentEmulateLayer::new(profile.clone()),
                EmulateTlsProfileLayer::new().with_builder_overwrites(tls_config),
            )
                .into_layer(service_fn(async |req: Request| {
                    // We dont set base emulator data here since we always use EmulateTlsProfileLayer, but we could
                    // set a base config here in case EmulateTlsProfileLayer would not always set a config.
                    let connector = HttpConnector::new(UserAgentEmulateHttpConnectModifier::new(
                        RequestVersionAdapter::new(TlsConnector::secure(
                            MockConnectorService::new(service_fn(server_svc_fn)),
                        )),
                    ))
                    .with_svc_req_inspector(UserAgentEmulateHttpRequestModifier::default());

                    let profile = req.extensions().get::<SelectedUserAgentProfile>().unwrap();
                    let expect_msg = format!("selected profile to work: {profile:?}");

                    let EstablishedClientConnection { req, conn } =
                        connector.serve(req).await.expect(&expect_msg);

                    Ok::<_, Infallible>(conn.serve(req).await.expect(&expect_msg))
                }));

            let expect_msg = format!("profile to work: {profile:?}");

            let mut server_extensions = Extensions::new();
            server_extensions.insert(State {
                counter: counter.clone(),
            });

            let req = Request::builder()
                .uri("https://www.example.com")
                .extension(ServerExtensions(server_extensions))
                .body(Body::empty())
                .expect(&expect_msg);

            client.serve(req).await.expect(&expect_msg);
        });
    }

    handles.join_all().await;

    assert_eq!(
        counter.load(std::sync::atomic::Ordering::Acquire),
        ua_db.len()
    );
}

struct MockConnectorService<S> {
    serve_svc: S,
}

impl<S: fmt::Debug> fmt::Debug for MockConnectorService<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MockConnectorService")
            .field("serve_svc", &self.serve_svc)
            .finish()
    }
}

impl<S> MockConnectorService<S> {
    fn new(serve_svc: S) -> Self {
        Self { serve_svc }
    }
}

#[derive(Clone, Default, Debug)]
/// [`ServerExtensions`] will be transfered from the client extensions to the server side
struct ServerExtensions(Extensions);

impl<S> Service<Request> for MockConnectorService<S>
where
    S: Service<Request, Response = Response, Error = Infallible> + Clone,
{
    type Error = S::Error;
    type Response = EstablishedClientConnection<MockSocket, Request>;

    async fn serve(&self, req: Request) -> Result<Self::Response, Self::Error> {
        let (client_socket, mut server_socket) = new_mock_sockets();

        if let Some(extensions) = req.extensions().get::<ServerExtensions>() {
            *server_socket.extensions_mut() = extensions.0.clone();
        }

        let svc = self.serve_svc.clone();

        tokio::spawn(async move {
            let server = TlsAcceptorLayer::new(
                ServerConfig {
                    application_layer_protocol_negotiation: Some(vec![
                        ApplicationProtocol::HTTP_2,
                        ApplicationProtocol::HTTP_11,
                    ]),
                    ..ServerConfig::new(ServerAuth::default())
                }
                .try_into()
                .unwrap(),
            )
            .with_store_client_hello(true)
            .into_layer(HttpServer::auto(Executor::default()).service(svc));
            server.serve(server_socket).await.unwrap();
        });

        Ok(EstablishedClientConnection {
            req,
            conn: client_socket,
        })
    }
}

use rama::net::test_utils::client::MockSocket;

fn new_mock_sockets() -> (MockSocket, MockSocket) {
    let (client, server) = duplex(1024);
    (MockSocket::new(client), MockSocket::new(server))
}
